package com.tio.server.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ssl.SslUtils;
import org.tio.http.common.HttpConfig;
import org.tio.http.server.handler.DefaultHttpRequestHandler;
import org.tio.server.TioServerConfig;
import org.tio.utils.SystemTimer;
import org.tio.utils.jfinal.P;
//import org.tio.utils.sub.mvc.TioDocs;

/**
 * @author tanyaowu
 * 2017年7月19日 下午4:59:04
 */
public class TioHttpServerStarter {

	private static Logger log = LoggerFactory.getLogger(TioHttpServerStarter.class);

	public static HttpConfig httpConfig;

	public static DefaultHttpRequestHandler requestHandler;

	public static org.tio.http.server.HttpServerStarter httpServer;

	public static TioServerConfig serverTioConfig;

	public static void start() throws Exception {

		long start = SystemTimer.currTime;
		int port = P.getInt("http.port");//启动端口
		String pageRoot = P.get("http.page");//html/css/js等的根目录，支持classpath:，也支持绝对路径
		httpConfig = new HttpConfig(port, true);
		httpConfig.setPageRoot(pageRoot);
		httpConfig.setMaxLiveTimeOfStaticRes(P.getInt("http.maxLiveTimeOfStaticRes"));
		httpConfig.setPage404(P.get("http.404"));
		httpConfig.setPage500(P.get("http.500"));
		httpConfig.setUseSession(false);
		httpConfig.setCheckHost(false);

		requestHandler = new DefaultHttpRequestHandler(httpConfig, TioHttpServerStarter.class);//第二个参数也可以是数组

//		TioDocs apiDoc = TioDocs.from(requestHandler.getRoutes().mvcTree);
//		log.warn(Json.toFormatedJson(apiDoc));

		httpServer = new org.tio.http.server.HttpServerStarter(httpConfig, requestHandler);
		serverTioConfig = httpServer.getTioServerConfig();
		serverTioConfig.setUseQueueDecode(true);
		httpServer.start(); //启动http服务器

		String protocol = SslUtils.isSsl(serverTioConfig) ? "https" : "http";
		long end = SystemTimer.currTime;
		long iv = end - start;
		log.info("Tio Http Server启动完毕,耗时:{}ms 访问地址:{}://127.0.0.1:{}", iv, protocol, port);

	}

}
